package com.hands.sample.handlers;

import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.impl.CanFulfillIntentRequestHandler;
import com.amazon.ask.dispatcher.request.handler.impl.IntentRequestHandler;
import com.amazon.ask.model.IntentRequest;
import com.amazon.ask.model.Response;
import com.amazon.ask.model.Slot;
import com.amazon.ask.model.canfulfill.CanFulfillIntentRequest;
import com.amazon.ask.response.ResponseBuilder;
import com.hands.sample.service.impl.JedisUtil;
import com.hands.sample.service.impl.WisdomHomeService;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Optional;
import static com.amazon.ask.request.Predicates.intentName;

public class ChatIntentHandler implements IntentRequestHandler {


    private static final Logger logger = LoggerFactory.getLogger(ChatIntentHandler.class);

    @Override
    public boolean canHandle(HandlerInput handlerInput, IntentRequest intentRequest) {
        if (intentRequest.getType().equals("IntentRequest"))
            return handlerInput.matches(intentName(intentRequest.getIntent().getName()));
        else
            return handlerInput.matches(intentName("chat"));
    }

    @Override
    public Optional<Response> handle(HandlerInput handlerInput, IntentRequest intentRequest) {
//        logC.writeFile("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"开始intentRequest时间："+logC.getCurrentYYYYMMDDHHMMSS()+"\r\n");
//        logC.writeFile("","handlerInput:"+handlerInput.toString()+"****请求内容:"+intentRequest.toString()+"\r\n");

        logger.info("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"开始intentRequest时间："+new Date());
        logger.info("","handlerInput:"+handlerInput.toString()+"****请求内容:"+intentRequest.toString());
        String deviceid=handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"speek";
        Slot slot = intentRequest.getIntent().getSlots().get("SlotName");
        String v = slot.getValue();
        JSONObject objV = JSONObject.fromObject(v);
        JSONObject returnMsg = new JSONObject();
        String speek="";
        try {
            String state="";
            Boolean MultiSession=Boolean.TRUE;
            if (JedisUtil.getInstance().get(deviceid)!=null)
                state=JedisUtil.getInstance().get(deviceid).toString();

            //logC.writeFile("",deviceid+"缓存数据："+state);
            logger.info("{}缓存的数据{}",deviceid,state);
            JedisUtil.getInstance().set(deviceid,"");
            if (state.length()>5) {
                JSONObject objstate = JSONObject.fromObject(state);
                state= objstate.get("speek").toString();
                ResponseBuilder response=handlerInput.getResponseBuilder();
                if (objstate.get("MultiSession")!=null)
                {
                    if (objstate.getString("MultiSession").equals("true"))
                        response.withShouldEndSession(Boolean.FALSE);
                }
                response.withSpeech(state);
                logger.info("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"响应技能时间："+new Date() +MultiSession+ "播报文字为："+state);
                //logC.writeFile("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"响应技能时间："+logC.getCurrentYYYYMMDDHHMMSS() +MultiSession+ "播报文字为："+state);
                return response.build();
            }

            logger.info("",deviceid+"直接触发了chat："+objV.get("query").toString());
            //logC.writeFile("",deviceid+"直接触发了chat："+objV.get("query").toString());
            JSONObject msg=new JSONObject();
            msg.put("query",objV.get("query").toString());
            msg.put("realm",intentRequest.getIntent().getName());
            returnMsg = WisdomHomeService.requestSound(handlerInput, msg.toString());
            ResponseBuilder response=handlerInput.getResponseBuilder();
            if (returnMsg.getString("sucess").equals("true"))
                speek=returnMsg.getString("speek");
            else
                speek = objV.get("answer").toString();
            if (returnMsg.get("MultiSession")!=null)
            {
                if (returnMsg.getString("MultiSession").equals("true"))
                    response.withShouldEndSession(Boolean.FALSE);
            }
            response.withSpeech(speek);
            logger.info("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"响应技能时间："+new Date() + "播报文字为："+speek);
            //logC.writeFile("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"响应技能时间："+logC.getCurrentYYYYMMDDHHMMSS() + "播报文字为："+speek);
            return response.build();//handlerInput.getResponseBuilder().withSpeech(speek).build();
        }  catch (Exception ex)
        {
            speek = objV.get("answer").toString();
            logger.info("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"出现异常："+new Date() + speek+"播报文字为："+ex.toString());
           // logC.writeFile("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"出现异常："+logC.getCurrentYYYYMMDDHHMMSS() + speek+"播报文字为："+ex.toString());
            ResponseBuilder response=handlerInput.getResponseBuilder();
            response.withSpeech(speek);
            return response.build();
        }
    }
}
